package com.zip.example.util;

import lombok.extern.slf4j.Slf4j;
import net.lingala.zip4j.core.ZipFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 *
 * @author zgq
 * @date 2020/11/5 12:25
 */
@Slf4j
public class FileUtils {

    /**
     * 解压缩
     *
     * @param zipPath    源路径
     * @param targetPath 目标路径
     * @return 操作结果
     */
    public static Boolean unzip(String zipPath, String targetPath) {
        try {
            ZipFile zipFile = new ZipFile(zipPath);
            zipFile.extractAll(targetPath);
            return true;
        } catch (Exception ex) {
            log.info("解压缩包失败：" + ex.getMessage());
            return false;
        }
    }

    /**
     * 获取给定路径下的所有子文件夹里面的文件
     *
     * @param path
     * @return
     */
    public static void getAllFile(String path, List<File> fileList) {
        File file = new File(path);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files == null) {
                return;
            }
            for (File fileT : files) {
                if (fileT.isDirectory()) {
                    getAllFile(fileT.getPath(), fileList);
                } else {
                    fileList.add(fileT);
                }
            }

        } else {
            fileList.add(file);
        }
    }

    /**
     * @param file 要删除的路径；删除给定路径下的所有文件和文件夹
     * @return 操作结果
     */
    public static Boolean deleteFile(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files.length != 0) {
                for (File file1 : files) {
                    if (file1.isDirectory()) {
                        deleteFile(file1);
                    } else {
                        boolean delete = file1.delete();
                    }

                }
                new File(file.getPath() + File.separator).delete();
            } else {
                new File(file.getPath() + File.separator).delete();
            }
        } else {
            boolean delete = file.delete();
        }
        return true;
    }


    public static void main(String[] args) {
        String path = "E:\\upload";
        List<File> fileList = new ArrayList<>();
        getAllFile(path, fileList);
        System.out.println(fileList);
    }
}
